<template>
  <div>
    <query-table v-if="loadInfo" ref="project_query_table" :page-size="-1" :columns="columns"
                  :table-max-height="tableMaxHeight"
                  :append-buttons="appendQueryButtons" :query-fields="queryFields"
                  dataRequestMethod="post"
                  :row-style="updateRowsStyle"
                  base-url="/project_info"
                  v-loading="isLoading" selectable show-index/>

    <el-dialog width="50%" title="导入数据" :visible="importDlgVisible"
               :close-on-click-modal="false" @close="importDlgVisible=false">
      <span slot="footer">
        <el-button v-if="importFileList && importFileList.length > 0"
                   type="primary" size="mini" @click="importData">确认导入</el-button>
      </span>
      <el-row>
        <el-col :span="12">
          <upload-dragger :file-list="importFileList" title="只能上传一个文件" :show-file-list="false" limit="1"/>
        </el-col>
        <el-col :span="12">
          <upload-dragger :file-list="importFileList" title="文件列表" :show-file-list="true" limit="1"/>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog width="90%" :title="(checkPermission('plan:update') && this.isInit)?'编辑方案':'查看方案'" v-loading="editCommonDlgLoading" :visible="editCommonDlgVisible"
               :close-on-click-modal="false" @close="editCommonDlgVisible=false">
      <span slot="footer">
        <el-button type="primary" size="mini" @click="saveBatchCommon" :disabled="!this.checkPermission('plan:update') || !this.isInit">保存</el-button>
        <el-button type="danger" size="mini" @click="editCommonDlgVisible = false">取消</el-button>
      </span>

      <div style="margin-bottom: 10px;">
        <span style="width:7px;background-color:#1E90FF;margin-right:3px;display:inline-block;float:left;height:18px;"/>
        基本信息
      </div>
      <custom-field-form  v-loading="editCommonDlgLoading" :fields="batchFields" :data="planInfo" size="small" >
        <el-checkbox  label="根据经济极限年判断评价期" v-model="planInfo.cutoff" style="margin-left: 40px;"></el-checkbox>
      </custom-field-form>
      <div style="margin-bottom: 10px;">
        <span style="width:7px;background-color:#1E90FF;margin-right:3px;display:inline-block;float:left;height:18px;"/>
        价格及商品率
      </div>
      <record-table ref="common_data_table" key="common_data_table" border-color="#ccc" :readonly="!this.isInit"
                    v-loading="editCommonDlgLoading" :data="commonDataList" :columns="commonDataColumns"
                    :max-height="300" show-index/>
    </el-dialog>

    <el-dialog width="90%" :title="(checkPermission('plan:update') && this.planInfo.state == 'init')?'编辑':'查看'"  v-loading="editProjectDlgLoading" :visible="editProjectDlgVisible"
               :close-on-click-modal="false" @close="editProjectDlgVisible=false">
      <span slot="footer">
        <el-button type="primary" size="mini" :disabled="!this.checkPermission('plan:update') || !this.isInit" @click="saveProject">保存</el-button>
        <el-button type="danger" size="mini" @click="editProjectDlgVisible = false">取消</el-button>
      </span>
      <el-tabs v-model="editTab" tab-position="left">
        <el-tab-pane label="基本信息" name="project">
          <custom-field-form  v-loading="editProjectDlgLoading" :rules="projectRules"
                              :fields="projectFields" :data="projectInfo" size="small" />
        </el-tab-pane>
        <el-tab-pane label="生产数据" name="yearRelated">
          <record-table ref="project_data_table" key="project_data_table" border-color="#ccc" :readonly="!this.checkPermission('plan:update') || !this.isInit"
                        v-loading="editProjectDlgLoading" :data="projectYearDataList" :columns="projectYearDataColumns"
                        :max-height="450" show-index/>
        </el-tab-pane>
        <el-tab-pane label="成本数据" name="cost" style="height: calc(75vh - 100px);overflow-y: auto;"   lazy>
          <page-part title="成本数据">
            <custom-field-form v-loading="editProjectDlgLoading"
                               :fields="projectCostFields" :data="projectCostData" size="small" />
          </page-part>
          <page-part title="税费数据">
            <custom-field-form v-loading="editProjectDlgLoading"
                               :fields="projectTaxFields" :data="projectCostData" size="small" />
          </page-part>
          <page-part title="固定参数">
            <custom-field-form v-loading="editProjectDlgLoading"
                               :fields="projectFixFields" :data="projectCostData" size="small" />
          </page-part>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-dialog width="90%" title="系数调整" v-loading="adjustRateDlgLoading" :visible="adjustRateDlgVisible"
               :close-on-click-modal="false" @close="adjustRateDlgVisible = false">
      <div>
            <custom-field-form size="small" :data="adjustRateFieldConditon" :fields="adjustRateFields" >
              <el-button size="small" type="success" @click="()=>{
                $refs['project_rate_table'].fillCellDataToBottom();
              }">向下填充</el-button>
              <el-button size="small" type="success" @click="()=>{
                $refs['project_rate_table'].fillCellDataToRight();
              }">向右填充</el-button>
            </custom-field-form>
      </div>
      <span slot="footer">
        <el-button type="primary" size="mini" @click="saveAdjustRate">保存</el-button>
        <el-button type="primary" size="mini" @click="()=>{
          this.saveAdjustRate('compute');

        }">批量计算</el-button>
        <el-button type="danger" size="mini" @click="adjustRateDlgVisible = false">取消</el-button>
      </span>
      <record-table ref="project_rate_table"
                    key="project_rate_table"
                    border-color="#ccc"
                    :data="adjustRatioDataMap[adjustRateType]"
                    :columns="projectRateColumns"
                    :max-height="450" show-index/>
    </el-dialog>
    <el-dialog width="90%" title="选择模板" v-loading="templateDlgLoading" :visible="templateDlgVisible"
               :close-on-click-modal="false" @close="templateDlgVisible=false">
      <span slot="footer">
        <el-button type="primary" size="mini" @click="commonExport">导出</el-button>
        <el-button type="danger" size="mini" @click="templateDlgVisible = false">取消</el-button>
      </span>
      <el-tabs v-model="editTemplateTab" tab-position="left">

        <el-tab-pane label="系统模板" name="system">
          <record-table ref="system_template_table" key="system_template_table" border-color="#ccc" :readonly="true"
                        v-loading="templateDlgLoading" :data="this.systemTemplateList" :columns="templateColumns"
                        @selection-change="systemSelectionChange"
                        :max-height="450" show-index showCheckbox/>
        </el-tab-pane>
        <el-tab-pane label="自定义模板" name="custom">
          <record-table ref="custom_template_table" key="custom_template_table" border-color="#ccc" :readonly="true"
                        v-loading="templateDlgLoading" :data="this.customTemplateList" :columns="templateColumns"
                        showCheckbox @selection-change="customSelectionChange"
                        :max-height="450" show-index/>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>
<script>
import UploadDragger from "../../components/upload-dragger";
import CustomFieldForm from "../../components/custom-field-form";
import DataSelect from "../../components/data-select";
export default {
  name: "PlanManage",
  components: {DataSelect, CustomFieldForm, UploadDragger},
  $$route:{
    meta:{
      title:'方案信息',
    }
  },
  props:{
    //页面高度
    pageHeight:{
      type:Number,
      default:500
    }
  },
  data() {
    return {
      isLoading:false,
      adjustRatioDataMap:{},
      isInit:false,
      adjustRateType:'output_ratio',
      adjustRateFields:[
        {
          id: 'adjustRateType',
          name: '调整系数',
          align: 'left',
          defaultValue:'output_ratio',
          component: {
            id: 'meta-select', type: 'adjust-ratio-type',load:this.loadAdjustRateType,change: (val) => {
               this.adjustRateType = val;
            }
          },
          colSpan: 8
        }
      ],
      adjustRateFieldConditon:{},
      editTemplateTab:'system',
      templateColumns:[
        {id: 'name', name: '项目名称', align:'left'},
        {id: 'createTime', name: '创建时间', colSpan: 8, disabled:true},
      ],
      columns: [
        {id: 'name', name: '名称', align:'left'},
        {id: 'year', name: '年度', width: 80},
        {id: 'passed', name: '达标情况',width:80,type:'meta',source:'pass-type',showOverflowTooltip:true},
        {id: 'evaluationMethod', name: '评价方式',width:80 ,type:'meta',source:'evaluation-method'},
        {id: 'totalInvest', name: '建设投资', unit:"万元", width:100,showOverflowTooltip:true},
        {id: 'afterTax', name: '税后', width: 120, children: [
            {id: 'irrAfterTax', name: '内部收益率', unit: "%", showOverflowTooltip: true},
            {id: 'pbpAfterTax', name: '投资回报期', unit: "年", showOverflowTooltip: true},
            {id: 'npvAfterTax', name: '财务净现值', unit: "万元", showOverflowTooltip: true},
          ]
        },
        {id: 'balance', name: '基准平衡', width: 120, children: [
            {id: 'balanceConstructionInvest', name: '建设投资', unit: "万元", showOverflowTooltip: true},
            {id: 'balanceSumGasOutput', name: '累产气', unit: "亿方", showOverflowTooltip: true},
          ],isHide:()=>{
            return this.planInfo.productType != 'gas'
          }
        },
        {id: 'balance', name: '基准平衡', width: 120, children: [
            {id: 'balanceConstructionInvest', name: '建设投资', unit: "万元", showOverflowTooltip: true},
            {id: 'balanceSumOilOutput', name: '累产油', unit: "万吨", showOverflowTooltip: true}
          ],isHide:()=>{
            return this.planInfo.productType != 'oil'
          }
        },
        {id: 'ultimate', name: '最终版本',width:80, showOverflowTooltip:true,formatter: (value) => {
            if (value === null) {
              return ''
            }

            return value?'是':'否';
          }
        },
        {
          id: 'operation', name: '操作', type: 'button', width:320,children: [
            {text: '编辑', type:'primary', click:(row)=>{this.editProject(row);},isHide:()=>{return !this.checkPermission('plan:update') || !this.isInit;}},
            {text: '查看', type:'primary', click:(row)=>{this.editProject(row);},isHide:()=>{return this.checkPermission('plan:update') && this.isInit;}},
            {text: '设为最终版', type:'primary', click:(row)=>{this.projectUltimate(row);},isHide:(row)=>{return !this.checkPermission('plan:update') ||
                  !this.isInit || !this.planInfo.versionId || row.ultimate;}},
            {text: '删除', type:'danger', click:(row)=>{this.deleteProject(row);},isHide:()=>{return !this.checkPermission('plan:update') || !this.isInit;}},
            {text: '评价结果',isHide: (row) => {return !row.computeId;},
              click:(row)=>{this.openPage('/evaluation/compute-invoke',row.id,{version:row.computeId})}},
          ]
        },
      ],

      importDlgVisible:false,
      importFileList:[],

      editCommonDlgLoading:true,
      editCommonDlgVisible:false,
      batchFields: [
        {
          id: 'name',
          name: '方案名称',
          rules: [{required: true, message: "请输入名称", trigger: "blur"}],
          colSpan: 8,
          isDisabled: () => {
            return !this.checkPermission('plan:update') ||  !this.isInit
          }
        },
        {
          id: 'paramVersion',
          name: '公共参数',
          rules: [{required: true, message: "请选择公共参数", trigger: "blur"}],
          colSpan: 9,
          isDisabled: () => {
          //  return !this.checkPermission('plan:update') ||  !this.isInit
            return true;
          },
          component: {
            id: 'data-select',
            dataUrl: '/settings/common_param_version/queryPublish'
          },
        },
        {
          id: 'modelId', name: '评价模型', disabled: true, colSpan: 7,
          isDisabled: () => {
           // return !this.checkPermission('plan:update') ||  !this.isInit
            return true
          },
          component: {
            id: 'data-select',
            dataUrl: '/settings/model/publish/data'
          },
        },
        {
          id: 'costEvaMethod',
          name: '成本测算方式',
          rules: [{required: true, message: "请选择成本测算方式", trigger: "blur"}],
          colSpan: 8,
          isDisabled: () => {
            return !this.checkPermission('plan:update') ||  !this.isInit
          },
          component: {id: 'meta-select', type: 'cost-eva-method'},
        },
        {
          id: 'createUser', name: '创建人', colSpan: 4,
          component: {
            id: 'data-select',
            disabled: true,
            requestMethod:'post',
            dataUrl: '/user/name_data?pageSize=-1'
          }
        },
        {id: 'createTime', name: '创建时间', colSpan: 5, disabled: true},
      ],
      planInfo:null,
      loadInfo:false,
      commonDataColumns:[
        {id: 'type', name: '参数名称',width:150, readonly:true},
        {id: 'year1', name: '第1年'},
        {id: 'year2', name: '第2年'},
        {id: 'year3', name: '第3年'},
        {id: 'year4', name: '第4年'},
        {id: 'year5', name: '第5年'},
        {id: 'year6', name: '第6年'},
        {id: 'year7', name: '第7年'},
        {id: 'year8', name: '第8年'},
        {id: 'year9', name: '第9年'},
        {id: 'year10', name: '第10年'},
        {id: 'year11', name: '第11年'},
        {id: 'year12', name: '第12年'},
        {id: 'year13', name: '第13年'},
        {id: 'year14', name: '第14年'},
        {id: 'year15', name: '第15年'},
        {id: 'year16', name: '第16年'},
        {id: 'year17', name: '第17年'},
        {id: 'year18', name: '第18年'},
        {id: 'year19', name: '第19年'},
        {id: 'year20', name: '第20年'}
      ],
      commonDataList:[
        {code:"oilPrice",           type:"原油价格（元/吨）"},
        {code:"gasPrice",           type:"天然气价格（元/千方）"},
        {code:"condensatePrice",    type:"轻烃价格（元/吨）"},
        {code:"liquidGasPrice",     type:"液化气价格（元/吨）"},
        {code:"oilCommodityRate",   type:"原油商品率（%）"},
        {code:"gasCommodityRate",   type:"天然气商品率（%）"},
        {code:"otherCommodityRate", type:"其他产品商品率（%）"},
      ],

      editProjectDlgLoading:false,
      editProjectDlgVisible:false,
      editTab:"project",
      projectRules: {
        evaluationPeriod:[{ validator: this.validatorIntegerNum, trigger: "blur" }],
        buildYearCount:[{ validator: this.validatorIntegerNum, trigger: "blur" }],
        newAnnualCapacity:[{ validator: this.validatorGatherZeroNum, trigger: "blur" }],
        newWellCount:[{ validator: this.validatorIntegerNum, trigger: "blur" }],
        outputWellOpenCount:[{ validator: this.validatorIntegerNum, trigger: "blur" }],
        injectWellOpenCount:[{ validator: this.validatorIntegerNum, trigger: "blur" }],
        drillExtractInvest:[{ validator: this.validatorGatherZeroNum, trigger: "blur" }],
        groundInvest:[{ validator: this.validatorGatherZeroNum, trigger: "blur" }],
        otherInvest:[{ validator: this.validatorGatherZeroNum, trigger: "blur" }],
        netAssetsUnUse:[{ validator: this.validatorGatherZeroNum, trigger: "blur" }],
      },
      projectFields:[
        {id: 'name', name: '名称',  rules: [{required: true, message: "请输入项目名称", trigger: "blur"}], colSpan: 16,isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        // {id: 'year', name: '项目年度', colSpan: 8, component:{id:'year-picker'},isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'evaluationPeriod', name: '评价期', colSpan: 8,  unit:"年",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'buildYearCount', name: '建设年限', colSpan: 8, unit:"年",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'evaluationMethod', name: '评价阶段', colSpan: 8, component:{id:'meta-select',type:'evaluation-method',load:this.methodBeforeDisplayList},isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'drillOilWellCount', name: '钻井油井数', colSpan: 8, unit:"口",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'drillWaterWellCount', name: '钻井水井数', colSpan: 8, unit:"口",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'drillWellCount', name: '钻井井数', colSpan: 8, unit:"口",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'straightWellDeth', name: '直井井深',  colSpan: 8, unit:"m",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'horizontalWellDeth', name: '水平井深',  colSpan: 8, unit:"m",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'intoRuler', name: '进尺',  colSpan: 8, unit:"10⁴m",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'infOilWellCount', name: '基建油井数',  colSpan: 8, unit:"口",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'infWaterWellCount', name: '基建水井数',  colSpan: 8, unit:"口",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'infWellCount', name: '基建井数',  colSpan: 8, unit:"口",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'builtUpCapacity', name: '建成能力',  colSpan: 8, unit:"10⁴m",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'wellOutput', name: '单井日产',  colSpan: 8, unit:"t",isDisabled:()=>{return!this.checkPermission('batch:update') ||  !this.isInit}},
        {id: 'straightWellOutput', name: '直井单井日产',  colSpan: 8, unit:"t",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'horizontalWellOutput', name: '水平单井日产',  colSpan: 8, unit:"t",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'horizontalWellCount', name: '钻水平井数',  colSpan: 8, unit:"口",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'buildHorizontalWellCount', name: '建水平井数',  colSpan: 8, unit:"口",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},

         {id: 'regionOilGasRate', name: '区块汽油比',  colSpan: 8, unit:"m³/t",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
         {id: 'oldNetWorth', name: '利用井净值',  colSpan: 8, unit:"万元",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
         {id: 'baseIrr', name: '基准收益率',  colSpan: 8, unit:"%",isDisabled:()=>{return !this.checkPermission('plan:update') ||  !this.isInit}},
        {id: 'resourceRate', name: '资源税',  colSpan: 8, unit:"%",isDisabled:()=>{return!this.checkPermission('batch:update') ||  !this.isInit}},
        {id: 'productionDay', name: '首年生产天数',  colSpan: 8, unit:"天",isDisabled:()=>{return!this.checkPermission('batch:update') ||  !this.isInit}},
        {id: 'createUser', name: '创建人', colSpan: 8, component: {
            id:'data-select',
            disabled:true,
            dataUrl:'/user/data?pageSize=-1'
        }},
        {id: 'createTime', name: '创建时间', colSpan: 8, disabled:true},
      ],
      projectTaxFields:[
        {id: 'oilValueAddedTaxRate', name: '原油增值税率',unit:'%',   colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'gasValueAddedTaxRate', name: '天然气增值税率',unit:'%',   colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'otherValueAddedTaxRate', name: '其他产品增值税率',unit:'%',   colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'cityConstructionTaxRate', name: '城市维护建设税率',unit:'%',   colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'educationSurchargeRate', name: '教育费附加税率',unit:'%',   colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'resourceTaxRate', name: '资源税率',unit:'%',   colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'incomeTaxRate', name: '所得税率',unit:'%',   colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
      ],
      projectFixFields:[
        {id: 'potionAmortisePeriod', name: '三元药剂摊销年限', unit:'年',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'iaAmortisePeriod', name: '无形资产摊销年限',  unit:'年', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'otherAssetsAmortisePeriod', name: '其他资产折旧年限', unit:'年',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'loanRepaymentPeriod', name: '借款偿还期', unit:'年',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'fixedAssetBorrowRatio', name: '固定资产借款比例', unit:'%',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'disposalFeeRatio', name: '弃置费提取比例', unit:'%',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'longTermLoanInterestRate', name: '长期贷款利率',  unit:'%', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'liquidBorrowInterestRate', name: '流动资金借款利率', unit:'%',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'liquidBorrowInterestRatio', name: '流动资金借款比例', unit:'%',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'liquidOfBusinessRatio', name: '流动资金占经营成本比例', unit:'%',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'costInputTaxOfOptRatio', name: '成本进项税占操作成本比例',  unit:'%', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'unitSellCost', name: '单位销售及管理费用', unit:'元/吨',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'surplusReserveRatio', name: '法定盈余公积金', unit:'%',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'exchangeRate', name: '汇率', unit:'人民币/美元',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'tonToBarrelRatio', name: '吨桶比',  unit:'桶/t', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'oilGasEquivalent', name: '油气当量', unit:'方/吨',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {
          id: 'condensateEquivalent', name: '凝析油当量', unit: '吨凝析油/吨油', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'otherManageCostConventional', name: '其他管理费（常规）', unit: '元/吨油', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'otherManageCostDeApportion', name: '其他管理费（扣分摊）', unit: '元/吨油', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'otherManageCostGround', name: '其他管理费（地面评价）', unit: '万元/人·年', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'gasManageCostConventional', name: '天然气其他管理费（常规）', unit: '元/万方', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'gasManageCostDeApportion', name: '天然气其他管理费（扣分摊）', unit: '元/万方', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'gasManageCostGround', name: '天然气其他管理费（地面评价）', unit: '万元/人·年', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'mineralResourcesComprate', name: '矿业权出让收益率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'businessCostRatio', name: '营业费用', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'safetyCostRatioOil', name: '安全生产费用（油）', unit: '元/吨', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'safetyCostRatioGas', name: '安全生产费用（气）', unit: '元/千方', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
      ],
      projectCostFields:[
        {id: 'operateCostStandard', name: '单井定额', unit:'万元/油井数',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'oilQuotaStandard', name: '吨油定额',  unit:'元/吨油', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'fixedCost', name: '固定成本', unit:'万元/油气井数',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'variableCost', name: '可变成本', unit:'元/吨油（元/万方）',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'miningOperationPrice', name: '采出作业费', unit:'万元/油井数',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'waterInjectionPrice', name: '驱油物注入费', unit:'元/方水',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'heavyOilThRecPrice', name: '稠油热采费',  unit:'元/吨蒸汽', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'oilGasProcessPrice', name: '油气处理费',  unit:'元/吨液', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'condensateRecyclePrice', name: '轻烃回收费',  unit:'元/吨油', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'underWellOperationPrice', name: '井下作业费', unit:'万元/油井数',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'wellTestPrice', name: '测井试井费',  unit:'万元/油井数', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'gasPurificationPrice', name: '天然气净化费',  unit:'元/千立方米',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'repairPrice', name: '维护及修理费',  unit:'万元/油井数', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'transferPrice', name: '运输费',  unit:'万元/总井数', colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'otherAuxiliaryPrice', name: '其他辅助作业费', unit:'万元/总井数',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},
        {id: 'factoryMineManagePrice', name: '厂矿管理费', unit:'万元/总井数',  colSpan: 12,isDisabled:()=>{return !this.checkPermission('batch:update') || !this.isInit}},

      ],
      projectInfo:{},
      projectCostData:[],
      projectYearDataColumns:[
        {id: 'type', name: '参数名称',width:150, readonly:true},
        {id: 'sum', name: '合计',width:65},
        {id: 'year1', name: '第1年',width:65},
        {id: 'year2', name: '第2年',width:65},
        {id: 'year3', name: '第3年',width:65},
        {id: 'year4', name: '第4年',width:65},
        {id: 'year5', name: '第5年',width:65},
        {id: 'year6', name: '第6年',width:65},
        {id: 'year7', name: '第7年',width:65},
        {id: 'year8', name: '第8年',width:65},
        {id: 'year9', name: '第9年',width:65},
        {id: 'year10', name: '第10年',width:65},
        {id: 'year11', name: '第11年',width:65},
        {id: 'year12', name: '第12年',width:65},
        {id: 'year13', name: '第13年',width:65},
        {id: 'year14', name: '第14年',width:65},
        {id: 'year15', name: '第15年',width:65},
        {id: 'year16', name: '第16年',width:65},
        {id: 'year17', name: '第17年',width:65},
        {id: 'year18', name: '第18年',width:65},
        {id: 'year19', name: '第19年',width:65},
        {id: 'year20', name: '第20年',width:65},
        {id: 'year21', name: '第21年',width:65},
        {id: 'year22', name: '第22年',width:65},
        {id: 'year23', name: '第23年',width:65},
        {id: 'year24', name: '第24年',width:65},
        {id: 'year25', name: '第25年',width:65},
        {id: 'year26', name: '第26年',width:65},
        {id: 'year27', name: '第27年',width:65},
        {id: 'year28', name: '第28年',width:65},
        {id: 'year29', name: '第29年',width:65},
        {id: 'year30', name: '第30年',width:65},
      ],
      projectYearDataList:[
        {code:"sumInvest", type:"合计投资（万元）"},
        {code:"drillExtractInvest", type:"钻采投资（万元）"},
        {code:"groundInvest",      type:"地面投资（万元）"},
        {code:"otherInvest",         type:"其他投资（万元）"},
       // {code:"productionRate",   type:"生产时率（%）"},
        {code:"outputWellOpenCount", type:"采出井开井数（口）"},
        {code:"injectionWellOpenCount", type:"注入井开井数（口）"},
        {code:"fixedPerson", type:"定员数（人）"},
        {code:"liquidOutput",     type:"产液量（万吨）"},
        {code:"oilOutput",        type:"原油产量（万吨）"},
        {code:"gasOutput",        type:"天然气产量（亿方）"},
        {code: "gasOutput1", type: "天然气产量（万方）"},
        {code:"waterInjection",   type:"注水量（万方）"},
        {code:"steamInjection",   type:"注蒸汽量（万吨）"},
        {code:"drugCost",         type:"药剂费（万元）"},
        {code:"condensateOutput", type:"轻烃产量（万吨）"},
        {code:"liquidGasOutput",  type:"液化气产量（万吨）"},
      ],
      templateDlgVisible:false,
      systemTemplateList: [],
      customTemplateList: [],
      multipleCustomSelection: [],
      multipleSystemSelection: [],
      templateDlgLoading: false,
      adjustRateDlgLoading:false,
      adjustRateDlgVisible:false,
      projectRateColumns:[
        {id: 'year', name: '项目年度',width:100, fixed:true, readonly:true},
        {id: 'name', name: '项目名称',width:120, fixed:true, showOverflowTooltip:true, readonly:true},
        {id: 'buildOffice', name: '建设单位', type:"office", fixed:true, showOverflowTooltip:true, width:120, readonly:true},
        {id: 'evaluationPeriod', name: '评价期',width:80, fixed:true, readonly:true},
        {id: 'year1', name: '第1年',width:65},
        {id: 'year2', name: '第2年',width:65},
        {id: 'year3', name: '第3年',width:65},
        {id: 'year4', name: '第4年',width:65},
        {id: 'year5', name: '第5年',width:65},
        {id: 'year6', name: '第6年',width:65},
        {id: 'year7', name: '第7年',width:65},
        {id: 'year8', name: '第8年',width:65},
        {id: 'year9', name: '第9年',width:65},
        {id: 'year10', name: '第10年',width:65},
        {id: 'year11', name: '第11年',width:65},
        {id: 'year12', name: '第12年',width:65},
        {id: 'year13', name: '第13年',width:65},
        {id: 'year14', name: '第14年',width:65},
        {id: 'year15', name: '第15年',width:65},
        {id: 'year16', name: '第16年',width:65},
        {id: 'year17', name: '第17年',width:65},
        {id: 'year18', name: '第18年',width:65},
        {id: 'year19', name: '第19年',width:65},
        {id: 'year20', name: '第20年',width:65}
      ],
      projectRateDataList:[],


    }
  },
  computed:{
    //表格最大高度，自适应
    tableMaxHeight(){
      return this.pageHeight - 150;
    },


    appendQueryButtons(){
      return [
        {text:'编辑方案',type:'success',click:this.editBatchCommonData,isHide:()=>{return !this.checkPermission('plan:update') ||  !this.isInit;}},
        {text:'查看方案',type:'success',click:this.editBatchCommonData,isHide:()=>{return this.checkPermission('plan:update') || this.isInit;}},
        {text:'系数调整',type:'success',click:this.initAdjustRate,listen:this.planInfo.state,isHide:()=>{return !this.checkPermission('plan:update') ||  !this.isInit;}},
        {text:'版本锁定',type:'success',click:() =>{this.openPage('/plan/lock',this.$route.query.id)},isHide:()=>{return !this.checkPermission('plan:update') ||  !this.isInit;}},
        {text:'批量计算',type:'success',click:this.batchCompute,isHide:()=>{return !this.checkPermission('plan:update') ||  !this.isInit;}},
        {text:'导入',type:'warning',click:() => {this.importDlgVisible = true},isHide:()=>{return !this.checkPermission('plan:update') || !this.isInit;}},
        {
          text: '导出', type: 'warning', click: () => {
            this.loadTemplate("export")
            this.templateDlgVisible = true
          },
          // tooltip: {content: '按照一个项目一行的方式将筛选后的项目批量导出到一个Excel工作表中。'}
        },
        {text:'生成报告',type:'warning',click:this.createReport,isHide:()=>{return !this.checkPermission('plan:update') || !this.isInit;}},
        {text:'下载报告',type:'warning',click:this.downloadReport},
      ];
    },
    queryFields() {
      let planName = ''
      let year = 0;
      let areaMark = ''
      if (this.planInfo) {
        planName = this.planInfo.name;
        year = this.planInfo.year
        areaMark = this.planInfo.areaMark;
      }

      return [

        {id: 'batchId', name: '方案id', hide:true,defaultValue:this.$route.query.id},
        {id: 'quality', name: '方案性质', hide:true,defaultValue:'plan'},
        {id: 'planNamed', name: '方案名称', colSpan: 8,disabled:true,defaultValue: planName},
        {id: 'productType', name: '原油类型', colSpan: 8,isHide: ()=> {return true}},


        {id: 'year', name: '年度', component: 'year-picker', colSpan: 4,disabled:true,defaultValue: year},
        {id: 'areaMark', name: '新老区', colSpan: 4,disabled:true, component: {id: 'meta-select', type: 'area-mark'},defaultValue: areaMark},
        {
          id: 'region',
          name: '大区',
          colSpan:4,
          listen: this.planInfo,
          defaultValue:this.planInfo.region,
          component: {
            id: 'data-select',
            getDataUrl: () => {
              return '/cascade/queryChildrenList?type=oil-region&parentSource=${productType}';
            },
            valueKey: 'source'
          },
          isHide: () => {
            return this.planInfo.productType == 'gas'
          },
          disabled: true
        },
        {
          id: 'region', name: '大区', colSpan: 4,
          defaultValue:this.planInfo.region,
          component: {
            id: 'data-select',
            getDataUrl: () => {
              return '/cascade/queryChildrenList?type=gas-region&parentSource=${productType}';
            },
            valueKey: 'source'
          }, isHide: () => {
            return this.planInfo.productType == 'oil'
          }, disabled: true
        },
        {
          id: 'capacityType',
          name: '产能类型',
          colSpan: 4,
          defaultValue:this.planInfo.capacityType,
          component: {id: 'meta-select', type: 'oil-capacity-type'},
          isHide: () => {
            return this.planInfo.productType == 'gas'
          }, disabled: true
        },
        {
          id: 'capacityType',
          name: '产能类型',
          colSpan:4,
          defaultValue:this.planInfo.capacityType,
          component: {id: 'meta-select', type: 'gas-capacity-type'},
          isHide: () => {
            return this.planInfo.productType == 'oil'
          }, disabled: true
        },
        {
          id: 'displacementMethod',
          name: '驱替方式',
          colSpan: 4,
          defaultValue:this.planInfo.displacementMethod,
          component: {id: 'meta-select', type: 'oil-displacement-method'},
          isHide: () => {
            return this.planInfo.productType == 'gas'
          }, disabled: true
        },
        {
          id: 'displacementMethod',
          name: '驱替方式',
          colSpan: 4,
          defaultValue:this.planInfo.displacementMethod,
          component: {id: 'meta-select', type: 'gas-displacement-method'},
          isHide: () => {
            return this.planInfo.productType == 'oil'
          }, disabled: true
        },
        {
          id: 'poolType',
          name: '油气藏类型',
          colSpan: 4,
          defaultValue:this.planInfo.poolType,
          component: {id: 'meta-select', type: 'oil-pool-type-new'},
          isHide: () => {
            return this.planInfo.productType == 'gas'
          }, disabled: true
        },
        {
          id: 'poolType',
          name: '油气藏类型',
          colSpan: 4,
          defaultValue:this.planInfo.poolType,
          component: {id: 'meta-select', type: 'gas-pool-type'},
          isHide: () => {
            return this.planInfo.productType == 'oil'
          },
          disabled: true
        },
        {id: 'buildOffice',
          name: '建设单位',
          disabled: true,
          defaultValue:this.planInfo.buildOffice,
          component: {
            id: 'company-select', hideRoot: true,load:(dataList)=>{
              let list=[]
              for (let item of dataList) {
                if (item.type =='sub_office') {
                  list.push(item)
                }
              }
              return list;
            }
          }, colSpan: 4},
        //{id: 'totalInvest', name: '建设投资', component: 'input-number-range', colSpan: 5},
      ];
    }

  },
  created() {
     this.loadPlanInfo()
   this.$nextTick(()=>{
     let table = this.$refs['project_query_table']

     table.updateQueryCondition('planNamed',this.planInfo.name);
     table.updateQueryCondition('year',this.planInfo.year);
     table.updateQueryCondition('areaMark',this.planInfo.areaMark);
     table.updateQueryCondition('region',this.planInfo.region);
     table.updateQueryCondition('capacityType',this.planInfo.capacityType);
     table.updateQueryCondition('displacementMethod',this.planInfo.displacementMethod);
     table.updateQueryCondition('poolType',this.planInfo.poolType);
     table.updateQueryCondition('buildOffice',this.planInfo.buildOffice);
   })

  },
  methods: {
    loadAdjustRateType(list) {
      let result = []
      for (let item of list) {
        if (item.id != 'cost_ratio') {
          result.push(item)
        }
      }
      return result
    },

    methodBeforeDisplayList(dataList) {
      let list =  []
      for (let i = 0; i < dataList.length; i++) {
        if (dataList[i].id != 'ground') {
          list.push(dataList[i])
        } else {
          if (dataList[i].id != 'optimize_invest') {
            list.push(dataList[i])
          }
        }
      }
      return list
    },
    updateRowsStyle({row, rowIndex}){
      if (row.ultimate && row.ultimate == true) {
        return {background: '#f0f9eb'}
      }
    },
    loadPlanInfo:function(){
      this.editCommonDlgLoading = true;
      this.$get("/plan_info/info/"+this.$route.query.id, {}, (response) => {
        this.planInfo = response.data;
        this.loadInfo = true
        this.planInfo.cutoff = true
        this.isInit = this.planInfo.state == 'init';
         // table.updateQueryCondition('productType',response.data.productType);
         // table.updateQueryCondition('productType',response.data.productType);
         // table.updateQueryCondition('productType',response.data.productType);
      },()=>{
        this.editCommonDlgLoading = false;
      });
      this.editCommonDlgLoading = false;
    },
    editBatchCommonData: function(){
      let commonDataDTO = {};
      commonDataDTO.pageSize = -1;
      commonDataDTO.pageNo = 1;
      commonDataDTO.batchId = this.$route.query.id;
      this.editCommonDlgVisible = true;
      this.editCommonDlgLoading = true;
      this.$get("/batch_common_data/data", commonDataDTO, (response) => {
        this.getBatchCommonDataForShow(response.data);
      },()=>{
        this.editCommonDlgLoading = false;
      });
    },
    getBatchCommonDataForShow(oriDataList){
      let yearPreFix = "year";
      let commonTableDataList = JSON.parse(JSON.stringify(this.commonDataList));
      for (const tableRow of commonTableDataList) {
        for (let i = 1; i < 21; i++) {
          let yearDatas = oriDataList.filter(item =>{return item[yearPreFix] == i});
          if(!yearDatas || yearDatas.length == 0){
            continue;
          }
          tableRow[yearPreFix + i] = yearDatas[0][tableRow.code];
        }
      }
      this.commonDataList = commonTableDataList;
    },
    importData(){
      let openLoading = this.openLoading("数据导入中···");
      this.$post("/plan_info/importExcel/"+this.importFileList[0].id+"/"+this.planInfo.id,
          {}, (response) => {
        this.$message.success("导入完成！");
        this.importDlgVisible = false;
        this.importFileList = [];
        this.$refs.project_query_table.reload();
        this.loadPlanInfo();
      }, (response) => {
        openLoading.close();
      });
    },
    saveBatchCommon:function () {
      let batchId = this.$route.query.id;
      //校验数据类型，并且生成组合新数据
      let yearPreFix = "year";
      let batchCommonList = [];
      for (let i = 1; i < 21; i++) {
        let entity = {batchId:batchId,year:i};
        for (let j = 0; j < this.commonDataList.length ; j++) {
          let dataInfo = this.commonDataList[j];
          let cellValue = dataInfo[yearPreFix + i];
          if(isNaN(cellValue)){
            this.$message.warning("第" + (j+1) + "行，【" + dataInfo.type + "】中，第" + i + "年数据不正确，请修改后重试！")
            return false
          }
          entity[dataInfo.code] = cellValue;
        }
        batchCommonList.push(entity);
      }
      this.planInfo.batchCommonDTOList = batchCommonList;
      this.editCommonDlgLoading = true;
      this.$post("/plan_info/edit_common", this.planInfo, (response) => {
        this.$message.success("保存成功！");
        this.editCommonDlgVisible = false;
        this.$refs['project_query_table'].reload();
      },()=>{
        this.editCommonDlgLoading = false;
      });
    },
    deleteProject(row){
      this.$confirm('即将删除项目【'+ row.name +'】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let openLoading = this.openLoading("数据删除中···");
        this.$post("/project_info/delete?id="+row.id, {}, (response) => {
          this.$message.success('删除成功!');
          this.$refs.project_query_table.reload();
        },()=>{
          openLoading.close();
        })
      }).catch(() => {});
    },
    projectUltimate(row) {
      row.ultimate = true;
      this.$post("/project_info/update",row,(res)=>{
        this.$message.success("保存成功");
        this.$refs.project_query_table.reload();
      })
    },
    editProject:async function(row){
      this.editTab = "project";
      this.editProjectDlgVisible = true;
      this.editProjectDlgLoading = true;
      this.projectInfo = row;
      let yearDataDTO = {};
      yearDataDTO.pageSize = -1;
      yearDataDTO.pageNo = 1;
      yearDataDTO.projectId = row.id;
      let responseYearData = await this.$getHttpPromise("/project_year_data/data",yearDataDTO);
      if(responseYearData.code == 0){
        this.getProjectYearDataForShow(responseYearData.data);
      }
      let responseCostData = await this.$getHttpPromise("/project/cost/info/"+this.projectInfo.id);
      if(responseCostData.code == 0){
        if (responseCostData.data) {
          this.projectCostData = responseCostData.data
        } else {
          this.projectCostData ={}
        }
      }
      this.editProjectDlgLoading = false;
    },
    getProjectYearDataForShow(oriDataList){
      let yearPreFix = "year";
      console.log('oriDataList',oriDataList)
      let projectYearDataList = JSON.parse(JSON.stringify(this.projectYearDataList));
      for (let j = projectYearDataList.length-1; j>=0; j--) {
        let tableRow = projectYearDataList[j];
        if (tableRow['code'] == 'gasOutput' && this.planInfo.productType == 'oil') {
          projectYearDataList.splice(j, 1)
          continue
        } else if (tableRow['code'] == 'gasOutput1' && this.planInfo.productType == 'gas') {
          projectYearDataList.splice(j, 1)
          continue
        }
        for (let i = 0; i < 30; i++) {
          let yearDatas = oriDataList.filter(item => {
            return item[yearPreFix] == i
          });
          if (!yearDatas || yearDatas.length == 0) {
            continue;
          }
          let getCode = tableRow.code
          if (tableRow['code'] == 'gasOutput1') {
            getCode = 'gasOutput'
          }

          let yearDatumElement = yearDatas[0][getCode];
          if (i == 0) {

              tableRow['sum'] = yearDatumElement

          } else {

              tableRow[yearPreFix + i] = yearDatumElement


          }

        }
      }
          this.projectYearDataList = projectYearDataList;
    },
    saveProject:function () {
      let batchId = this.$route.query.id;
      let yearPreFix = "year";
      //校验数据类型，并且生成组合新数据
      let yearDataList = [];
      for (let i = 1; i < 21; i++) {
        let entity = {batchId:batchId,year:i};
        for (let j = 0; j < this.projectYearDataList.length ; j++) {
          let dataInfo = this.projectYearDataList[j];
          let cellValue = dataInfo[yearPreFix + i];
          if(isNaN(cellValue)){
            this.$message.warning("第" + (j+1) + "行，【" + dataInfo.type + "】中，第" + i + "年数据不正确，请修改后重试！")
            return false
          }
          entity[dataInfo.code] = cellValue;
        }
        yearDataList.push(entity);
      }
      this.projectInfo.yearDataDTOList = yearDataList;
      this.projectInfo.projectCostData = this.projectCostData;
      this.editProjectDlgLoading = true;
      this.$post("/project_info/edit_project", this.projectInfo, (response) => {
        this.$message.success("保存成功！");
        this.editProjectDlgVisible = false;
        this.$refs['project_query_table'].reload();
      },()=>{
        this.editProjectDlgLoading = false;
      });
    },
    systemSelectionChange(val) {
      this.multipleSystemSelection = val
    },
    customSelectionChange(val) {
      this.multipleCustomSelection = val
    },
    loadTemplate(exportTemplateType) {
      this.loadSystemTemplate(exportTemplateType);
      this.loadCustomTemplate(exportTemplateType);
    },
    loadSystemTemplate(exportTemplateType) {
      this.$get("/template/data", {
        type: 'system',
        tag: this.planInfo.productType,
        publish: true,
        exportTemplateType: exportTemplateType
      }, (res) => {
        this.systemTemplateList = res.data;
      })
    },
    loadCustomTemplate(exportTemplateType) {
      this.$get("/template/data", {
        type: 'custom',
        tag: this.planInfo.productType,
        publish: true,
        exportTemplateType: exportTemplateType
      }, (res) => {
        this.customTemplateList = res.data;
      })
    },
    commonExport() {
      if ((!this.multipleSystemSelection || this.multipleSystemSelection.length <= 0) &&
          (!this.multipleCustomSelection || this.multipleCustomSelection.length <= 0)) {
        this.$message.warning('未选中任何行');
        return;
      }
      if ((this.multipleSystemSelection && this.multipleSystemSelection.length > 0) &&
          (this.multipleCustomSelection && this.multipleCustomSelection.length > 0)) {
        this.$message.warning('只允许选择一个模板');
        return;
      }
      if ((this.multipleSystemSelection && this.multipleSystemSelection.length > 1) ||
          (this.multipleSystemSelection && this.multipleCustomSelection.length > 1)) {
        this.$message.warning('只允许选择一个模板');
        return;
      }
      let template = null;
      if (this.multipleSystemSelection) {
        template = this.multipleSystemSelection[0]
      } else {
        template = this.multipleCustomSelection[0]
      }
      this.exportData(template.id)
      this.templateDlgVisible = false;
    },
    exportData(){
      let projectList = this.$refs['project_query_table'].getDataList();
      let idList = []
      for (let item of projectList) {
        idList.push(item.id)
      }
      window.open(Vue.prototype.$ctx+'/plan_info/exportExcel?batchId='+  this.$route.query.id +'&idList='+idList+'&templateId='+'21dba941a1e64abb92bc19206db052fe');
    },
    //生成报告
    createReport() {
      this.loadingText = '正在计算...';
      if (!this.planInfo.versionId){
        this.$message.warning("请先计算项目再生成报告")
        return
      }
      const loading = this.openLoading("正在处理,请稍后...");
      this.$get("/project/report/createReport"  , {planId:this.planInfo.id,versionId:this.planInfo.versionId}, (response) => {
        this.$message.success('保存成功！');
      },()=>{
        loading.close();
      });
    },
    downloadReport(){
      if (!this.planInfo.versionId){
        this.$message.warning("请先计算项目，生成报告后在下载报告")
        return
      }
      window.open(this.$ctx+'/project/report/download?planId=' + this.planInfo.id);
    },
     buildUrl  (path, query) {
      if (!(query)) {
        console.error('请传入正确的query')
        return
      }
      let str = ''
      Object.keys(query).forEach(key => {
        str += `&${key}=${encodeURIComponent(query[key])}`
      })
      return `${path}?${str.slice(1)}`
    },

    saveAdjustRate(type) {
      this.adjustRateDlgLoading = true;
      let map = {}
      for (let item of  this.adjustRatioDataMap['cost_ratio']) {

        if(!map[item['projectId']]){
          map[item['projectId']]=[]
        }
         for (let itemkey in item) {
           if (itemkey.indexOf('year') >=0 && itemkey != 'year')
           map[item['projectId']].push(itemkey)
         }


      }
      let dataList = []
      for (let key in map) {

        let yearList = map[key];
        for (let yearCol of yearList) {
          let data = {}
          data['projectId'] = key;
          for (let item of this.adjustRatioDataMap['cost_ratio']) {
            if (item['projectId'] != key) {
              continue
            }
            let year = yearCol.replace('year', '')
            data['year'] = parseInt(year);
            data['costRatio'] = parseFloat(item[yearCol])
          }
          for (let item of this.adjustRatioDataMap['output_ratio']) {
            if (item['projectId'] != key) {
              continue
            }
            data['outputRatio'] = parseFloat(item[yearCol])
          }
          for (let item of this.adjustRatioDataMap['invest_ratio']) {
            if (item['projectId'] != key) {
              continue
            }
            data['investRatio'] = parseFloat(item[yearCol])
          }
          dataList.push(data)
        }
      }

      this.$post('/project_year_data/saveRatio',dataList,(res) => {


          if (type =='compute') {
            this.batchCompute();
          } else {
            this.$message.success("保存成功")
          }


      },()=>{
        this.adjustRateDlgLoading = false;
        this.adjustRateDlgVisible=false;
      });
    },
    initAdjustRate() {
      this.adjustRateDlgVisible = true;
      this.adjustRateDlgLoading = true;
      let projectList = this.$refs['project_query_table'].getDataList();
      let projectIds = [];
      if (projectList) {
        for (let item of projectList){
          projectIds.push(item.id)
        }
      }

      this.$post("/project_year_data/queryRatio", projectIds, (response) => {
          this.adjustRatioDataMap = response.data;
      //  this.adjustRateDlgLoading = false;
      },()=>{
        this.adjustRateDlgLoading = false;
      });

    },
    //批量计算
    batchCompute() {
      const loading = this.openLoading('正在处理，请稍后...');
      let projectList = this.$refs['project_query_table'].getDataList();
      let projectIdList = [];
      for(let item of projectList) {
        projectIdList.push(item.id)
      }
      this.$post('/compute_version/batch/invoke',{batchId:this.planInfo.id,filterProjectSet:projectIdList,quality:'plan'},(response)=>{
        this.$message.success("计算完成")
        this.loadPlanInfo()
        this.$refs.project_query_table.reload();
      },(response)=>{
        loading.close();
      })
    }
  },

}
</script>
